package gy.com.sansharescuesystem.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

/**
*Json解析工具类
*@author huangbo
*create at 2016/10/21 9:41
*/
public class GsonUtils {

    private static final Gson mGson = new Gson();

    public static <T> T json2Bean(String json, Class<T> clazz) {
        try {
            return mGson.fromJson(json, clazz);
        } catch (Exception e) {
            LogUtils.error(e.toString());
            return null;
        }

    }

    public static <T> T jsonBean(String json, Class<T> clazz) {
        try {
            Gson gson = new Gson();
            java.lang.reflect.Type type = new TypeToken<T>() {}.getType();
            T obj = gson.fromJson(json, type);
            return obj;
        } catch (Exception e) {
            LogUtils.error(e.toString());
            return null;
        }

    }
    public static <T>List<T> json2List(String json, Class<T> clazz) {
        List<T> list = new ArrayList<>();
        try{
            list = mGson.fromJson(json,new TypeToken<List<T>>(){}.getType());
        }catch (Exception e){
            LogUtils.error(e.toString());
        }
        return list;
    }

    /**
     * toJson
     * @param src src
     * @return String
     */
    public static String bean2Json(Object src) {
        return mGson.toJson(src);
    }
}
